import type { ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { DetailItem, ParkingOrderTableListItem, QueryListParams, zoneId } from './data';
import type { RequestData } from '@ant-design/pro-table';
import { message } from 'antd';
import { request } from 'umi';

/**
 * 获取流水列表
 * @param params
 */
export async function queryParkingList(
  params: { order_no?: string; zone: zoneId } & QueryListParams,
): Promise<RequestData<ParkingOrderTableListItem>> {
  // const [startTimeRangeStart, startTimeRangeEnd] = params.inTime || [];
  const res: ResponsePaginationData<any> = await request(`/parking/v2/page_list`, {
    params: {
      order_no: params.order_no,
      zone_id: params.zone ? params.zone.id || '' : undefined,
      page: params.page,
      pageSize: params.pageSize,
    },
  });

  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map((item) => ({
      ...item,
    })),
  };
}
// 查询详情
export async function queryParkTurnoverDetail(params: {
  id: number;
}): Promise<{ success: boolean; data?: DetailItem }> {
  const res = await request(`/parking/v2/${params.id}`);
  if (!res || res.code !== SUCCESS_CODE || !res.data) {
    message.error('获取失败');
    return { success: false };
  }
  return {
    success: true,
    data: {
      ...res.data,
    },
  };
}

// 结束停车
export async function parkExit(params: { id: number }) {
  const formatDate = () => {
    const date = new Date();
    return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '-');
  };
  const res = await request(`/parking/v2/${params.id}/stop`, {
    method: 'POST',
    data: {
      end_time: formatDate(),
    },
  });
  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}
